/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SMART_SERVE_SERVICES_SERVER_SERVICE_MAINTAINER_H
#define SMART_SERVE_SERVICES_SERVER_SERVICE_MAINTAINER_H

#include "assertion.h"
#include <atomic>
#include <condition_variable>
#include <list>
#include <mutex>
#include <thread>

namespace OHOS {
namespace SmartServe {

class Maintainer {
public:
    using TaskType = std::function<void()>;

    Maintainer()
    {
        thread_ = std::thread([this]() { ThreadMain(); });
    }

    ~Maintainer()
    {
        ASSERT(!thread_.joinable() && "Must call `Terminate` before destruction!");
    }

    void Terminate()
    {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            terminating_ = true;
        }
        cv_.notify_all();
        thread_.join();
    }

    void AddTask(TaskType&& task)
    {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            tasks_.push_back(task);
        }
        cv_.notify_all();
    }

private:
    std::mutex mutex_;
    std::condition_variable cv_;

    std::list<TaskType> tasks_;
    std::thread thread_;

    std::atomic_bool terminating_{false};

    void ThreadMain()
    {
        while (true) {
            TaskType task;
            {
                std::unique_lock<std::mutex> lock(mutex_);
                cv_.wait(lock, [this]() { return !tasks_.empty() || terminating_; });

                if (terminating_) {
                    return;
                }

                task = tasks_.front();
                tasks_.pop_front();
            }

            task();
        }
    }
};

} // namespace SmartServe
} // namespace OHOS

#endif // SMART_SERVE_SERVICES_SERVER_SERVICE_MAINTAINER_H
